package com.evry.spring3sandbox.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import com.evry.spring3sandbox.domain.Customer;
import com.evry.spring3sandbox.domain.Order;
import com.evry.spring3sandbox.domain.Product;

@Repository("orderDao")
public class JdbcOrderDao extends JdbcDaoSupport implements OrderDao {

	@Autowired
	public JdbcOrderDao(DataSource dataSource) {
		setDataSource(dataSource);
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<Order> getOrdersByCustomer(Customer customer) {
		List<Order> orders = getJdbcTemplate().query(
				"select o.id as orderId, o.customerId as customerId, o.productId as productId, p.name as name, p.description as description, p.price as price from orders as o left join products as p on o.productId=p.id where o.customerId = "
						+ customer.getId(), new OrderMapper(customer));
		
		for (Order order : orders) {
			System.out.println("FROM DAO after query: " + order.toString());
		}
		
		return orders;
	}

	private class OrderMapper implements ParameterizedRowMapper<Order> {
		private Customer customer;
		OrderMapper(Customer customer) {
			this.customer = customer;
		}
		
		public Order mapRow(ResultSet rs, int rowNum) throws SQLException {
			Order order = new Order();
			order.setId(rs.getInt("orderId"));
			order.setCustomerId(rs.getInt("customerId"));
			order.setProductId(rs.getInt("productId"));
			Product product = new Product();
			product.setId(rs.getInt("productId"));
			product.setName(rs.getString("name"));
			product.setDescription(rs.getString("description"));
			product.setPrice(rs.getDouble("price"));
			order.setProduct(product);
			order.setCustomer(customer);
			return order;
		}

	}

	@Override
	public void deleteOrder(Integer id) {
		String deleteStatement = "DELETE FROM orders WHERE id = " + id;
		getJdbcTemplate().update(deleteStatement);
	}
}
